﻿using System;

namespace NamedBinaryTag
{
	/// <summary>
	/// Represents a Tag containing a String.
	/// </summary>
	public sealed class TagString : NamedTag, IValueTag<string>
	{
		private string _value;

		public string Value
		{
			get { return _value; }
			set { if (_value != value) { _value = value; RaisePropertyChange("Value"); } }
		}

		public override byte TagType
		{
			get { return 8; }
		}

		public override void Read(System.IO.BinaryReader input, bool ignoreName)
		{
			base.Read(input, ignoreName);
			TagShort length = new TagShort();
			length.Read(input, true);
			Value = new string(System.Text.Encoding.UTF8.GetChars(input.ReadBytes(length.Value)));
		}

		public override void Write(System.IO.BinaryWriter output, bool ignoreName)
		{
			base.Write(output, ignoreName);
			TagShort length = new TagShort();
			string value = Value;
			if (value == null) value = string.Empty;
			byte[] vBytes = System.Text.Encoding.UTF8.GetBytes(value);
			length.Value = (short)Math.Min(vBytes.Length, (int)short.MaxValue);
			length.Write(output, true);
			output.Write(vBytes, 0, length.Value);
		}

		public override string ToString()
		{
			return string.Format("TagString {{ Name = \"{0}\", Value = \"{1}\" }}", Name, _value);
		}
	}
}
